<template>
    <u-upload style="flex: 0; margin: 10px" @afterRead="afterRead" @delete="deletePic" :maxCount="maxCount || 1">
        <u-button type="primary" :text="text"></u-button>
    </u-upload>
</template>

<script>
import { policy } from '../../lib/service';
export default {
    name: 'image-uploader',
    props: ['type', 'fileName', 'maxCount', 'text'],
    data() {
        return {
            images: []
        };
    },
    methods: {
        deletePic(event) {
            this.images.splice(event.index, 1);
            this.$emit('change', this.images);
        },
        update() {
            this.$emit('change', this.images);
        },
        // 新增图片
        async afterRead(event) {
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [event.file];
            let fileListLen = this.images.length;
            lists.map((item) => {
                this.images.push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i]);
                let item = this.images[fileListLen];
                this.images.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: 'success',
                        message: '',
                        url: result
                    })
                );
                fileListLen++;
                this.update();
            }
        },
        uploadFilePromise(file) {
            let name = file.name ? file.name : file.url.split('/').pop();
            if (this.fileName) {
                name = this.fileName + '.' + name.split('.').pop();
            }
            return new Promise((resolve, reject) => {
                policy(this.type, name).then((res) => {
                    let a = uni.uploadFile({
                        url: res.data.signedUrl, // 仅为示例，非真实的接口地址
                        filePath: file.url,
                        name: 'file',
                        success: (res) => {
                            try {
                                var data = JSON.parse(res.data);
                                resolve(data.data);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    });
                });
            });
        }
    }
};
</script>

<style></style>
